package com.moko.view;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.moko.R;
import com.moko.common.AsyncImageLoader;
import com.moko.common.AsyncImageLoaderCallback;

public class GridViewAdapter extends BaseAdapter {
	private LayoutInflater inflater;
	private JSONArray array;
	private AsyncImageLoader loader;

	public GridViewAdapter(JSONArray array, Context context, AsyncImageLoader loader) {
		inflater = LayoutInflater.from(context);
		this.array = array;
		this.loader = loader;
	}

	@Override
	public int getCount() {
		if (null != array) {
			return array.length();
		} else {
			return 0;
		}
	}

	@Override
	public Object getItem(int position) {
		try {
			return array.get(position);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// 不使用缓存，每个channel_item都new出来
		convertView = inflater.inflate(R.layout.channel_item, null);
		GridViewHolder viewHolder = new GridViewHolder();
		viewHolder.name = (TextView) convertView.findViewById(R.id.name);
		viewHolder.duty = (TextView) convertView.findViewById(R.id.duty);
		viewHolder.image = (ImageView) convertView.findViewById(R.id.image);
		// 使用缓存的，貌似图片加载有问题，容易加载乱
		// ViewHolder viewHolder;
		// if (convertView == null) {
		// convertView = inflater.inflate(R.layout.channel_item, null);
		// viewHolder = new ViewHolder();
		// viewHolder.name = (TextView) convertView.findViewById(R.id.name);
		// viewHolder.duty = (TextView) convertView.findViewById(R.id.duty);
		// viewHolder.image = (ImageView) convertView.findViewById(R.id.image);
		// convertView.setTag(viewHolder);
		// } else {
		// viewHolder = (ViewHolder) convertView.getTag();
		// }
		JSONObject object;
		try {
			object = (JSONObject) array.get(position);
			convertView.setTag(object.getString("href"));
			viewHolder.name.setText(">" + object.getString("name"));
			viewHolder.duty.setText(object.getString("rank") + "  " + object.getString("duty"));
			AsyncImageLoaderCallback callbackImpl = new AsyncImageLoaderCallback(viewHolder.image);
			Bitmap cacheImage = loader.loadBitmap(object.getString("src2"), callbackImpl);
			if (null != cacheImage) {
				viewHolder.image.setImageBitmap(cacheImage);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return convertView;
	}

	class GridViewHolder {
		public TextView name;
		public TextView duty;
		public ImageView image;
	}
}